#include "stdafx.h"
#include "segline.h"

/* p0p1 x p0p2  = x1y2 - x2y1 */
int CalcCrossMulti(T_Point& p0, T_Point& p1, T_Point p2)
{
	int x1y2 = (p1.x - p0.x) * (p2.y - p0.y);
	int x2y1 = (p2.x - p0.x) * (p1.y - p0.y);

	return x1y2 - x2y1;
}

bool CrossLine(T_Line& lineA, T_Line& lineB)
{
	int temp1 = CalcCrossMulti(lineA.tStart, lineB.tStart, lineB.tEnd);
	int temp2 = CalcCrossMulti(lineA.tEnd, lineB.tStart, lineB.tEnd);

	return (bool)(temp1 * temp2 < 0);
}

bool PointOnLine(T_Point& pt, T_Line& line)
{
	int temp1 = CalcCrossMulti(pt, line.tStart, line.tEnd);

	int temp2 = (pt.x - line.tStart.x) * (pt.x - line.tEnd.x);
	int temp3 = (pt.y - line.tStart.y) * (pt.y - line.tEnd.y);

	return (bool)(temp1 == 0 && temp2 <= 0 && temp3 <= 0);
}

bool SegLineInterSect(T_Line& lineA, T_Line& lineB)
{
	bool bLineCross = (bool)(CrossLine(lineA, lineB) && CrossLine(lineB, lineA));
	bool bPointOnLine = (bool)(PointOnLine(lineA.tStart, lineB)
		|| PointOnLine(lineA.tEnd, lineB)
		|| PointOnLine(lineB.tStart, lineA)
		|| PointOnLine(lineB.tEnd, lineA));

	return (bool)(bLineCross || bPointOnLine);
}

void RandSet(T_Point& pt)
{
	pt.x = rand() % 10;
	pt.y = rand() % 10;
}

void RandSet(T_Line& line)
{
	RandSet(line.tStart);
	RandSet(line.tEnd);
}